package com.yc.atm;

import com.google.gson.Gson;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @program: concurrent
 * @description:
 * @author: zy
 * @create: 2022-01-15 10:48
 */
public class BankTask implements Runnable{
    private Socket socket;
    private Bank b;
    private boolean flag;

    public BankTask(  Socket s, Bank b ){
        this.socket=s;
        this.b=b;
        this.flag=true;
    }
    @Override
    public void run() {
        try(
                // 因为要用到tr..resource直接关闭socket, 所以要将 socket重新在try注册
                Socket s=this.socket;
                Scanner reader=new Scanner(  s.getInputStream() );
                PrintWriter pw=new PrintWriter(   s.getOutputStream() );
         ){
            while( flag&&  ! Thread.currentThread().isInterrupted()  ){
                //客户端是否没有传数据，如没有传，则结束
                if(     !reader.hasNext()){
                    System.out.println("atm客户端:"+s.getRemoteSocketAddress()+"掉线了");
                    break;
                }
                //如果有信息，则取出
                String command=reader.next();    //next()读第一个部分，而没有读取一行.
                BankAccount ba=null;

                JsonModel<BankAccount> jm=new JsonModel<BankAccount>();
                //命令模式:
                if("DEPOSIT".equals(command)){
                   int id=  reader.nextInt();
                   double money=reader.nextDouble();
                   ba=b.deposite(id, money);
                }else if("WITHDRAW".equals(command)){
                    int id=  reader.nextInt();
                    double money=reader.nextDouble();
                    ba=b.withdraw(id, money);
                }else if("BALANCE".equals(command)){
                    int id=  reader.nextInt();
                    ba=b.search(id);
                }else if(  "QUIT".equals(command)){
                    System.out.println("atm客户端要求主要断开..."+ s.getRemoteSocketAddress());
                    break;
                }else{
                    //pw.println("错误命令 ");
                    jm.setCode(0);
                    jm.setErrorMsg("错误命令");

                    Gson g=new Gson();
                    String jsonString= g.toJson( jm);
                    pw.println(   jsonString    );
                    pw.flush();
                    continue;
                }
                //TODO: 将基本字符串改为 json，这样数据丰富.
               // pw.println(  ba.getId()+" "+ ba.getBalance() );

                jm.setCode(1);
                jm.setObj(  ba );

                Gson g=new Gson();
                String jsonString= g.toJson( jm);
                pw.println(   jsonString    );
                pw.flush();

            }


        }catch(  Exception ex ){
            ex.printStackTrace();

        }
    }
}
